/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PersonUI.java
 *
 * Created on 2010.11.10., 1:19:14
 */
package workshopdesign.UI;

import java.util.Collection;
import javax.swing.JOptionPane;
import javax.swing.RowFilter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableRowSorter;
import org.jdesktop.application.Action;
import workshopdesign.Control.AddressController;
import workshopdesign.Control.LoanController;
import workshopdesign.Model.Person;

/**
 *
 * @author Dom
 */
public class PersonUI extends javax.swing.JPanel implements BaseUIController {

    private AddressController address_controller = AddressController.getAddressController();
    private PersonDetailUI personDetailUI;
    private DVDDetailUI dVDDetailUI;
    private LoanListUI loanListUI;
    private DefaultTableModel model;
    private TableRowSorter<DefaultTableModel> sorter;

    /** Creates new form PersonUI */
    public PersonUI() {
        initComponents();

        dVDDetailUI = new DVDDetailUI(this, "Borrowed DVD", false);
        personDetailUI = new PersonDetailUI(this, "Details", true);
        loanListUI = new LoanListUI(this, "Loans");

        person_detail_splitter.setTopComponent(personDetailUI);
        person_loan_splitter.setTopComponent(loanListUI);
        person_loan_splitter.setBottomComponent(dVDDetailUI);

        model = (DefaultTableModel) person_table.getModel();
        
        sorter = new TableRowSorter<DefaultTableModel>(model);
        person_table.setRowSorter(sorter);

        filter_field.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void insertUpdate(DocumentEvent e) {
                filter_data();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                filter_data();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                filter_data();
            }
        });

        DefaultTableColumnModel columnModel = new DefaultTableColumnModel();
        TableColumn id_column = new TableColumn(0, 25);
        id_column.setHeaderValue("Id");
        columnModel.addColumn(id_column);
        
        TableColumn name_column = new TableColumn(1, 75);
        name_column.setHeaderValue("Name");
        columnModel.addColumn(name_column);

        TableColumn address_column = new TableColumn(2, 75);
        address_column.setHeaderValue("Address");
        columnModel.addColumn(address_column);

        TableColumn city_column = new TableColumn(3, 75);
        city_column.setHeaderValue("City");
        columnModel.addColumn(city_column);

        person_table.setAutoCreateColumnsFromModel(false);
        person_table.setColumnModel(columnModel);

        load_person_list();

        loanListUI.setPerson(null);
    }

    private void load_person_list() {
        Collection<Person> person_list = address_controller.listAllPersons();

        model.setRowCount(person_list.size());

        int row_id = 0;
        for (Person person : person_list) {
            model.setValueAt(person.getId(), row_id, 0);
            model.setValueAt(person.getName(), row_id, 1);
            model.setValueAt(person.getAddress(), row_id, 2);
            model.setValueAt(person.getCity(), row_id, 3);
            model.setValueAt(person.getPostalCode(), row_id, 4);
            model.setValueAt(person.getPhone(), row_id, 5);
            model.setValueAt(person.getEmail(), row_id, 6);

            row_id++;
        }
    }

    private void filter_data(){
        sorter.setRowFilter(RowFilter.regexFilter(".*" + filter_field.getText() + ".*"));
    }

    @Override
    public void update_data() {
        load_person_list();
    }

    @Override
    public void clear_selection() {
        person_table.clearSelection();
        loanListUI.clear();
    }

    @Override
    public void subselection_changed() {
        dVDDetailUI.setDvd(loanListUI.get_dvd_for_selected_loan());
    }

    public void handle_selection() {
        int selected_row = person_table.getSelectedRow();

        if (selected_row < 0) {
            personDetailUI.setPerson(null);
            return;
        }

        long person_id = Long.valueOf(String.valueOf(model.getValueAt(selected_row, 0)));
        Person person = address_controller.getPerson(person_id);

        personDetailUI.setPerson(person);
        loanListUI.setPerson(person);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        person_context_menu = new javax.swing.JPopupMenu();
        delete_menu_item = new javax.swing.JMenuItem();
        person_splitter = new javax.swing.JSplitPane();
        person_detail_splitter = new javax.swing.JSplitPane();
        person_loan_splitter = new javax.swing.JSplitPane();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        person_table = new javax.swing.JTable();
        filter_field = new javax.swing.JTextField();
        filter_label = new javax.swing.JLabel();

        person_context_menu.setName("person_context_menu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(workshopdesign.WorkshopDesignApp.class).getContext().getActionMap(PersonUI.class, this);
        delete_menu_item.setAction(actionMap.get("delete_person")); // NOI18N
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(workshopdesign.WorkshopDesignApp.class).getContext().getResourceMap(PersonUI.class);
        delete_menu_item.setText(resourceMap.getString("delete_menu_item.text")); // NOI18N
        delete_menu_item.setName("delete_menu_item"); // NOI18N
        person_context_menu.add(delete_menu_item);

        setName("Form"); // NOI18N
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        person_splitter.setDividerLocation(550);
        person_splitter.setName("person_splitter"); // NOI18N

        person_detail_splitter.setDividerLocation(220);
        person_detail_splitter.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        person_detail_splitter.setName("person_detail_splitter"); // NOI18N

        person_loan_splitter.setDividerLocation(200);
        person_loan_splitter.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        person_loan_splitter.setName("person_loan_splitter"); // NOI18N

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel2.border.title"))); // NOI18N
        jPanel2.setName("jPanel2"); // NOI18N

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        jList1.setName("jList1"); // NOI18N
        jScrollPane2.setViewportView(jList1);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 161, Short.MAX_VALUE)
                .addContainerGap())
        );

        person_loan_splitter.setTopComponent(jPanel2);

        person_detail_splitter.setRightComponent(person_loan_splitter);

        person_splitter.setRightComponent(person_detail_splitter);

        jPanel1.setName("jPanel1"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        person_table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Name", "Address", "City", "Postal code", "Phone", "Email"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Long.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        person_table.setComponentPopupMenu(person_context_menu);
        person_table.setName("person_table"); // NOI18N
        person_table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        person_table.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                person_tableMousePressed(evt);
            }
        });
        jScrollPane1.setViewportView(person_table);

        filter_field.setText(resourceMap.getString("filter_field.text")); // NOI18N
        filter_field.setName("filter_field"); // NOI18N

        filter_label.setText(resourceMap.getString("filter_label.text")); // NOI18N
        filter_label.setName("filter_label"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(filter_label)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(filter_field, javax.swing.GroupLayout.DEFAULT_SIZE, 517, Short.MAX_VALUE))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 549, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(filter_field, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(filter_label))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 608, Short.MAX_VALUE))
        );

        person_splitter.setLeftComponent(jPanel1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 809, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(0, 0, 0)
                    .addComponent(person_splitter, javax.swing.GroupLayout.DEFAULT_SIZE, 809, Short.MAX_VALUE)
                    .addGap(0, 0, 0)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 636, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(0, 0, 0)
                    .addComponent(person_splitter, javax.swing.GroupLayout.DEFAULT_SIZE, 636, Short.MAX_VALUE)
                    .addGap(0, 0, 0)))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void person_tableMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_person_tableMousePressed
        handle_selection();
    }

    @Action
    public void borrow_menu_item() {
        // NOTE: Not used!
    }//GEN-LAST:event_person_tableMousePressed

    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        load_person_list();
        personDetailUI.load_data();
        loanListUI.load_data();
        dVDDetailUI.load_data();
    }//GEN-LAST:event_formComponentShown

    @Action
    public void delete_person() {
        int selected_row = person_table.getSelectedRow();

        if (selected_row < 0) {
            return;
        }

        long person_id = Long.valueOf(String.valueOf(model.getValueAt(selected_row, 0)));

        int answer = JOptionPane.showConfirmDialog(
                this,
                "Do you really want to delete this person? ID=" + String.valueOf(person_id),
                "Delete person",
                JOptionPane.YES_NO_OPTION);

        if (answer != JOptionPane.YES_OPTION) {
            return;
        }

        LoanController.getLoanController().deleteLoansByPerson(person_id);

        address_controller.deletePerson(person_id);

        load_person_list();
        handle_selection();
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem delete_menu_item;
    private javax.swing.JTextField filter_field;
    private javax.swing.JLabel filter_label;
    private javax.swing.JList jList1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JPopupMenu person_context_menu;
    private javax.swing.JSplitPane person_detail_splitter;
    private javax.swing.JSplitPane person_loan_splitter;
    private javax.swing.JSplitPane person_splitter;
    private javax.swing.JTable person_table;
    // End of variables declaration//GEN-END:variables
}
